package com.wxh.lock;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @ClassName: TestCyclicBarrier
 * @Description: 循环栅栏: 学生去饭店吃饭
 * @Author wxh
 * @Date: 2022/2/9 16:21
 * @Version V1.0.0
 * @Since 1.8
 */
public class TestCyclicBarrier {
    private CyclicBarrier cyclicBarrier = new CyclicBarrier(5);

    public static void main(String[] args) {
        new TestCyclicBarrier().begin();
    }

    private class Student implements Runnable{
        @Override
        public void run() {
            System.out.println("学生去饭店吃饭");
            try {
                // 模拟学生走在路上
                Thread.sleep(1000);
                // 人到了就等着，等其他人都到了，再进饭店
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            System.out.println("所有人都到了，进饭店吃饭");
        }
    }

    private void begin(){
        for (int i = 0; i < 5; i++) {
            new Thread(new Student()).start();
        }
    }
}
